package com.project.web.wechat.controller.app.cpWeChat;

import com.project.common.core.utils.exception.Result;
import com.project.web.config.WxCorp.WxCpConfig;
import com.project.web.config.WxCorp.WxCpConfiguration;
import com.project.web.util.exception.WeChatCustomException;
import com.project.web.wechat.controller.common.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 身份验证控制器
 *
 * @author wyy
 * @date 2020-06-24
 */
@Api(tags = "身份验证接口")
@RestController("workWxOauth2Controller")
@RequestMapping("/weChat/auth/workWx/oauth2")
public class WorkWxOauth2Controller extends BaseController {

    /**
     * 构建网页授权链接
     *
     * @param redirectUri 授权后重定向的回调链接地址
     * @param state       重定向后会带上state参数
     * @param scope       应用授权作用域:[snsapi_base]
     * @return
     */
    @ApiOperation("构建网页授权链接")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "redirectUri", value = "授权后重定向的回调链接地址", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "state", value = "重定向后会带上state参数", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "scope", value = "应用授权作用域:[snsapi_base]", required = true, dataType = "String")
    })
    @PostMapping(value = "/buildAuthorizationUrl")
    public Result<String> buildAuthorizationUrl(String redirectUri, String state, String scope, HttpServletRequest request) {
        try {
            redirectUri = URLDecoder.decode(redirectUri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        String authorizationUrl = wxCpService.getOauth2Service().buildAuthorizationUrl(redirectUri, state, scope);
        return getResult(authorizationUrl);
    }

    /**
     * 根据code返回用户信息
     *
     * @param code 成员授权获取到的code
     * @return
     */
    @ApiOperation("根据code获取用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "code", value = "授权后重定向的回调链接地址", required = true, dataType = "String")
    })
    @PostMapping(value = "/getUserInfo")
    public Result<WxCpOauth2UserInfo> getUserInfo(String code, HttpServletRequest request) {

        // 企业微信基本参数
        Map<Object, Object> returnMap = new HashMap<>();
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        try {
            WxCpOauth2UserInfo userInfo = wxCpService.getOauth2Service().getUserInfo(code);
            return getResult(userInfo);
        } catch (WxErrorException e) {
            log.error("根据code获取用户信息出错：{}", ExceptionUtils.getStackTrace(e));
            throw new WeChatCustomException(String.valueOf(e.getError().getErrorCode()), e.getError().getErrorMsg());
        }
    }

    /**
     * 构造扫码登录链接
     *
     * @param redirectUri 授权后重定向的回调链接地址
     * @param state       重定向后会带上state参数
     * @return
     */
    @ApiOperation("构造扫码登录链接")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "redirectUri", value = "授权后重定向的回调链接地址", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "state", value = "重定向后会带上state参数", required = true, dataType = "String"),
    })
    @PostMapping(value = "/qrConnect")
    public Result<String> qrConnect(String redirectUri, String state, HttpServletRequest request) {
        try {
            redirectUri = URLDecoder.decode(redirectUri, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 企业微信基本参数
        WxCpConfig wxCpConfig = getWxCpConfig(request);
        WxCpService wxCpService = WxCpConfiguration.getCpService(wxCpConfig.getCorpId(), wxCpConfig.getAgentId());
        String authorizationUrl = wxCpService.getOauth2Service().buildAuthorizationUrl(redirectUri, state);
        return getResult(authorizationUrl);
    }

}
